package com.taotao.common.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

/**
 * Created by zhang_xming on 2017/3/18.
 */
@Configuration
//@ComponentScan(basePackages = "com.taotao.content.service")
@EnableTransactionManagement
public class TransactionConfig {
    @Bean(name = "dataSourceTransactionManager")
    public DataSourceTransactionManager transactionManager(DruidDataSource dataSource) {
        http://log.info("TransactionManager 初始化");
        return new DataSourceTransactionManager(dataSource);
    }
    //platformTransactionManager 为springboot默认初始化好的对象，，无需定义
    @Bean(name = "transactionInterceptor")
//    @ConditionalOnClass(PlatformTransactionManager.class)
    public TransactionInterceptor transactionInterceptor(
            DataSourceTransactionManager dataSourceTransactionManager) {
        System.out.println("+++++++++++++哈哈哈哈哈哈啊哈");
        TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
        // 事物管理器
        transactionInterceptor.setTransactionManager(dataSourceTransactionManager);
        Properties transactionAttributes = new Properties();

        // 新增
        transactionAttributes.setProperty("insert*",
                "PROPAGATION_REQUIRED,-Throwable");
        // 新增
        transactionAttributes.setProperty("add*",
                "PROPAGATION_REQUIRED,-Throwable");
        // 修改

        transactionAttributes.setProperty("update*",
                "PROPAGATION_REQUIRED,-Throwable");
        // 删除
        transactionAttributes.setProperty("delete*",
                "PROPAGATION_REQUIRED,-Throwable");
        //查询
        transactionAttributes.setProperty("select*",
                "PROPAGATION_REQUIRED,-Throwable,readOnly");

        transactionInterceptor.setTransactionAttributes(transactionAttributes);
        return transactionInterceptor;
    }
    //代理到ServiceImpl的Bean
    @Bean
    public BeanNameAutoProxyCreator transactionAutoProxy() {
        BeanNameAutoProxyCreator transactionAutoProxy = new BeanNameAutoProxyCreator();
        transactionAutoProxy.setProxyTargetClass(true);
        transactionAutoProxy.setBeanNames("*ServiceImpl");
        transactionAutoProxy.setInterceptorNames("transactionInterceptor");
        return transactionAutoProxy;
    }

}